using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Plan;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_ViewModel
{
    public class SelectSalesOrderViewModel : BaseViewModel
    {
        #region 事件
        public event Action<SalesOrderModel>? OrderSelected;
        #endregion

        #region 私有字段
        private readonly SalesOrderService _salesOrderService;
        private string _searchSalesCode = string.Empty;
        private string _searchSalesName = string.Empty;
        private SalesOrderModel? _selectedOrder;
        private ObservableCollection<SalesOrderModel> _salesOrders = new();
        private bool _isLoading = false;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalCount = 0;
        private int _totalPage = 0;
        #endregion

        #region 公共属性
        public string SearchSalesCode
        {
            get => _searchSalesCode;
            set => SetProperty(ref _searchSalesCode, value);
        }

        public string SearchSalesName
        {
            get => _searchSalesName;
            set => SetProperty(ref _searchSalesName, value);
        }

        public SalesOrderModel? SelectedOrder
        {
            get => _selectedOrder;
            set 
            { 
                SetProperty(ref _selectedOrder, value);
                ((RelayCommand)ConfirmCommand).RaiseCanExecuteChanged();
            }
        }

        public ObservableCollection<SalesOrderModel> SalesOrders
        {
            get => _salesOrders;
            set => SetProperty(ref _salesOrders, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPage
        {
            get => _totalPage;
            set => SetProperty(ref _totalPage, value);
        }

        /// <summary>
        /// 分页信息显示
        /// </summary>
        public string PageInfo => $"第 {CurrentPage} 页，共 {TotalPage} 页，总计 {TotalCount} 条记录";

        /// <summary>
        /// 是否可以转到上一页
        /// </summary>
        public bool CanGoPreviousPage => CurrentPage > 1;

        /// <summary>
        /// 是否可以转到下一页
        /// </summary>
        public bool CanGoNextPage => CurrentPage < TotalPage;
        #endregion

        #region 命令
        public ICommand SearchCommand { get; }
        public ICommand ResetCommand { get; }
        public ICommand ConfirmCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }
        #endregion

        #region 构造函数
        public SelectSalesOrderViewModel()
        {
            _salesOrderService = new SalesOrderService();
            
            SearchCommand = CreateCommand(ExecuteSearchAsync);
            ResetCommand = CreateCommand(ExecuteResetAsync);
            ConfirmCommand = CreateCommand(ConfirmSelection, () => SelectedOrder != null);
            
            // 分页命令
            FirstPageCommand = CreateCommand(() => _ = GoToPageAsync(1), () => CanGoPreviousPage);
            PreviousPageCommand = CreateCommand(() => _ = GoToPageAsync(CurrentPage - 1), () => CanGoPreviousPage);
            NextPageCommand = CreateCommand(() => _ = GoToPageAsync(CurrentPage + 1), () => CanGoNextPage);
            LastPageCommand = CreateCommand(() => _ = GoToPageAsync(TotalPage), () => CanGoNextPage);

            // 初始加载数据
            LoadDataAsync();
        }
        #endregion

        #region 私有方法
        private async void LoadDataAsync()
        {
            try
            {
                IsLoading = true;
                var (orders, totalCount, totalPage) = await _salesOrderService.GetSalesOrdersAsync(
                    SearchSalesCode, SearchSalesName, CurrentPage, _pageSize);
                
                SalesOrders = new ObservableCollection<SalesOrderModel>(orders);
                TotalCount = totalCount;
                TotalPage = totalPage;
                
                OnPropertyChanged(nameof(PageInfo));
                OnPropertyChanged(nameof(CanGoPreviousPage));
                OnPropertyChanged(nameof(CanGoNextPage));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载销售订单数据失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async void ExecuteSearchAsync()
        {
            CurrentPage = 1; // 重置到第一页
            await SearchOrdersAsync();
        }

        private async void ExecuteResetAsync()
        {
            SearchSalesCode = string.Empty;
            SearchSalesName = string.Empty;
            CurrentPage = 1;
            await SearchOrdersAsync();
        }

        private async Task SearchOrdersAsync()
        {
            try
            {
                IsLoading = true;
                var (orders, totalCount, totalPage) = await _salesOrderService.GetSalesOrdersAsync(
                    SearchSalesCode, SearchSalesName, CurrentPage, _pageSize);
                
                SalesOrders = new ObservableCollection<SalesOrderModel>(orders);
                TotalCount = totalCount;
                TotalPage = totalPage;
                
                OnPropertyChanged(nameof(PageInfo));
                OnPropertyChanged(nameof(CanGoPreviousPage));
                OnPropertyChanged(nameof(CanGoNextPage));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"搜索销售订单失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task GoToPageAsync(int pageNumber)
        {
            if (pageNumber >= 1 && pageNumber <= TotalPage && pageNumber != CurrentPage)
            {
                CurrentPage = pageNumber;
                await SearchOrdersAsync();
            }
        }

        private void ConfirmSelection()
        {
            if (SelectedOrder != null)
            {
                OrderSelected?.Invoke(SelectedOrder);
            }
        }
        #endregion
    }
}





